<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="排班制" name="team">
        <el-row :gutter="20" class="mb20">
          <el-col :span="4">
            <el-date-picker style="width: 100%" v-model="req.month" value-format="yyyy-MM" type="month" placeholder="选择月" :clearable="false" @change="monthChange"></el-date-picker>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-search" @click="monthChange(req.month)">查询</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="人员制" name="member">
        <el-row :gutter="20" class="mb20">
            <el-col :span="4">
                <SelectWorkList v-model="teamId" :label.sync="teamName" @onLoad="onLoad" @change="search()"></SelectWorkList>
            </el-col>
          <el-col :span="4">
            <el-date-picker style="width: 100%" v-model="req.month" value-format="yyyy-MM" type="month" placeholder="选择月" :clearable="false" @change="monthChange"></el-date-picker>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-search" @click="monthChange(req.month)">查询</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <div class="scroll-content" :loading="loading">
      <div class="row">
        <div class="title" style="font-size: 15px;">排班制{{activeName=='team'?'班组':'人员'}}</div>
        <div class="col" :style="index == monthDay.length - 1 ? 'border-right: 1px solid #e5e5e5;' : ''" v-for="(item, index) in monthDay" :key="index">
          {{ item.day }}{{ item.week }}
        </div>
      </div>

      <div class="row" @mousedown="onmousedown" v-for="(row, i) in list" :key="i" :ref="i">
        <div class="title" :class="getClass(row)">{{ row.teamName || row.memberName }}</div>
        <template v-for="(item, index) in row.workList">
          <div :key="i +'-'+ index" :class="[item.sel ? 'col col-sel' : 'col', item.checked ? 'checked' : '', index == monthDay.length - 1 ? 'last-node' : '']" :style="getStyles(item)" :data-row="(row.teamId||row.memberId)" :data-col="index" :data-attr="item.timeHour ? parseSeconds(item.timeHour) : ''">
            {{getTimes(item.timeSegment).join('\n')}}
          </div>
        </template>
      </div>
    </div>
    <!-- 弹窗 -->
    <edit :show.sync="show" :item="current" :clazz="activeName" :teamId="teamId" :teamName="teamName" @change="getList"></edit>

    <Popper :show="showPoper" :styles="styles" :item="currentItem" @del="del"></Popper>
  </div>
</template>

<script>
import SelectWorkList from './components/selectWorkList.vue'
import Popper from "@/components/Popper/index.vue";
import edit from "./components/edit.vue";
import { workListByGroup,workListByMember, workDel } from "@/api/workShift";
import { classList } from "@/api/classGroup";
import { parseSeconds } from "@/utils";
export default {
  components: {
    Popper,
    edit,
    SelectWorkList
  },
  data() {
    return {
        loading: false,
      monthDay: [],
      show: false,
      current: null,
      list: [],
      total: 0,
      isMove: false,
      req: {
        month: null,
        workTeamId: null,
      },
      teamId: null,
      teamName: null,
      showPoper: false,
      styles: {},
      currentItem: {},
      activeName: "team",
    };
  },
  created() {
    const date = new Date();
    const month = date.getMonth() + 1;
    const month0 = month < 10 ? "0" + month : month;
    this.monthChange(date.getFullYear() + "-" + month0);
  },
  beforeDestroy() {},
  methods: {
    parseSeconds,
    classList,
    handleClick() {
        if(this.activeName == 'member') {
            if(!this.teamId) {
                this.list = [];
                return;
            };
        }
        this.getList()
    },
    onLoad(e) {
        if(this.activeName == 'team') return;
        this.getList()
    },
    search() {
        this.monthChange(this.req.month)
    },
    monthChange(e) {
      if (!e) return;
      this.req.month = e;
      this.getList();
      const arr = e.split("-");
      const dayCount = new Date(
        arr[0],
        arr[1].length < 2 ? "0" + arr[1] : arr[1],
        0
      ).getDate();
      this.monthDay = [];
      for (var i = 1; i <= dayCount; i++) {
        const day = i < 10 ? "0" + i : i.toString();
        const workDay = e + "-" + day;
        const week = this.parseTime(workDay, "周{a}");
        const sel = false;
        this.monthDay.push({
          day,
          workDay,
          week,
          sel,
        });
      }
    },

    onmousedown(e) {
      this.showPoper = false;
      if (!e.target.dataset.row) return;
      if (e.button == 2) {
        e.target.addEventListener("contextmenu", (event) => {
          event.preventDefault();
        //   console.log("右键");
          this.current = this.list.find(item => (item.teamId||item.memberId) == e.target.dataset.row);
          this.currentItem = this.current.workList[e.target.dataset.col];
          this.styles.top = e.clientY + "px";
          this.styles.left = e.clientX + "px";
          this.showPoper = true;
          return;
        });
      } else if (e.button == 0) {
        this.current = this.list.find(item => (item.teamId||item.memberId) == e.target.dataset.row);
        this.editList = [];
        this.isMove = true;
        window.addEventListener("mousemove", this.onmousemove, false);
        window.addEventListener("mouseup", this.onmouseup, false);
      }
    },
    onmousemove(e) {
      if (!this.isMove) return;
      if (!e.target.dataset.row || !e.target.dataset.col) return;
      if (e.target.dataset.col == this.lastCol) return;
      this.lastCol = e.target.dataset.col;
      if (this.current && (this.current.teamId||this.current.memberId) != e.target.dataset.row) {
        this.onmouseup(e);
      } else {
        this.current.workList[e.target.dataset.col].sel = true;
        this.editList.push(this.current.workList[e.target.dataset.col]);
      }
      this.$forceUpdate();
    },
    onmouseup(e) {
      this.isMove = false;
      if (this.lastCol) {
        // 多选
        let work = null;
        this.editList.forEach((item) => {
          if (!work) {
            work = item;
            work.dayList = [];
          }
          work.dayList.push(item.workDay);
        });
        work.day = work.dayList.join(",");
        delete work.dayList;

        console.log('team:',this.teamId, this.teamName)
        this.edit(work);
      } else {
      }

      this.lastCol = null;
      window.removeEventListener("mousemove", this.onmousemove);
      window.removeEventListener("mouseup", this.onmouseup);
    },
    // 获取列表
    async getList() {
        try {
            this.loading = true;
            const res = this.activeName == 'team'?await workListByGroup(this.req) :await workListByMember({...this.req, teamId: this.teamId})
            if(res.data && res.data.length) {
                res.data.forEach((item) => {
                    item.workList = JSON.parse(JSON.stringify(this.monthDay));

                    //   console.log(item.workList);
                    item.list = item.list || [];
                    item.workList.forEach((day) => {
                        day.teamId = item.teamId;
                        day.teamName = item.teamName;
                        day.memberId = item.memberId;
                        day.memberName = item.memberName;
                        const temp = item.list.find(e => this.parseTime(e.day, "{y}-{m}-{d}") == day.workDay);
                        if (temp) {
                            day.color = temp.color;
                            day.checked = true;
                            day.timeSegment = temp.timeSegment;
                            day.id = temp.id;
                            day.segmentType = temp.segmentType;
                            day.timeHour = temp.timeHour;
                        } else {
                            day.segmentType = 0;
                            day.checked = false;
                            day.timeSegment = "";
                            day.timeHour = "";
                        }
                    });
                });
                    this.list = res.data || [];
                    this.total = res.total;
                }else{
                    this.list = []
                }

                this.loading = false;
            } catch (error) {
                this.loading = false;
            }
    },
    getTimes(list) {
      if (!list) return [];
      const _list = JSON.parse(list);
      return _list.map((item) => {
        const name = item.name ? item.name+' ':''
        return (
            name+
          this.formatTimeHM(item.startTime) +
          "-" +
          this.formatTimeHM(item.endTime)
        );
      });
    },
    formatTimeHM(timeString) {
      const [hours, minutes, seconds] = timeString.split(":");

      // 创建一个日期对象，将时分秒设置为对应的值
      const date = new Date();
      date.setHours(hours);
      date.setMinutes(minutes);

      // 使用toLocaleTimeString方法将时间格式化为时分的字符串
      const formattedTime = date.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });

      return formattedTime;
    },
    // 添加
    add() {
      this.current = {};
      this.show = true;
    },
    // 删除
    del(item) {
      this.$modal.confirm("确定删除此条数据吗？").then((res) => {
        // 请求服务器删除数据
        workDel({
          id: item.id,
        }).then((res) => {
          this.showPoper = false;
          // 刷新数据
          this.getList();
        });
      });
    },
    // 修改
    edit(item) {
      this.current = JSON.parse(JSON.stringify(item));
      this.show = true;
    },
    getStyles(item) {
      if (item.color)
        return {
          background: item.color,
        };
      return {};
    },
    getClass(row) {
        let name = row.teamName || row.memberName;
        return name.length > 10 ? 'small-size' : ''
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .scroll-content {
    height: 680px;
    overflow: auto;
    position: relative;
  }

  .row {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    flex-wrap: nowrap;

    &:first-of-type {
      position: sticky;
      top: 0;
      z-index: 8;

      .col {
        background: #f7f6fb;
      }
    }

    .col {
      white-space: pre-line;
      cursor: pointer;
      padding: 0 2px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      min-width: 100px;
      height: 80px;
      border: 1px solid #e5e5e5;
      border-right: none;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      box-sizing: border-box;
      background: #fff;
      &:before {
        content: attr(data-attr);
        font-size: 12px;
      }
      &.checked {
        font-size: 10px;
        color: #fff;
        background: #188fffe0;
      }

      &-sel {
        font-size: 12px;
        color: #fff;
        background-color: #67c23a !important;
      }

      .times-mini {
        font-size: 10px;
      }

      &.last-node {
        border-right: 1px solid #e5e5e5;
      }
    }

    .title {
      display: flex;
      align-items: center;
      padding: 7px 10px;
      border: 1px solid #e5e5e5;
      border-right: none;
      width: 100px;
      height: 80px;
      flex-shrink: 0;
      overflow: hidden;
      position: sticky;
      left: 0;
      background: #f7f6fb;
      box-sizing: border-box;

      &.small-size {
        font-size: 12px;
      }
    }

    .btn {
      border: 1px solid #e5e5e5;
      cursor: pointer;
      padding: 10px;
      width: 25px;
      height: 50px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #1890ff;

      &-danger {
        background-color: #f00;
      }
    }
  }
}
</style>
